var ParkDataDictList = function (targetObj) {
    this.sysUtils = new kendoUtils();
    this.targetObj = targetObj;
    this.init();
    return this;
};

ParkDataDictList.prototype = {
    init: function () {
        var bindFieldArray = this.sysUtils.getBindFieldArray(this.targetObj.find(".search-panel"));
        var bindFunctionArray = [{fName: "queryInfo", fs: this.findGridData}, {fName: "resetInfo", fs: this.resetInfo}];
        this.bindBaseModels = new bindBaseModel(null, bindFieldArray, bindFunctionArray, null);
        this.sysUtils.bindDoucment(this.bindBaseModels, this.targetObj, this);
        this.treeView();
        this.createGrid();
    },
    treeView: function () {
        var that = this;
        let url = baseApiPath + "basSystemDataDict/selectAll";
        JsonpAjax(url, null, function (result) {
            if (0 === result.code) {
                if (result.constructor == Object) {
                    that.targetObj.find("#dataDictTreeView").kendoTreeView({
                        dataTextField: "fullName",
                        dataSource: result,
                        schema: {
                            model: {
                                hasChildren: "hasChildren",
                                id: "id",
                                children: "items",
                                expanded: "expanded"
                            }
                        }, select: function (e) {
                            var dataItem = this.dataItem(e.node);
                            that.nodeInfo = dataItem;//保存选中树节点信息
                            that.findGridData(null, dataItem.dataCode);
                        },
                        dataBound: function (e) {
                            //默认选中根节点
                            if (that.nodeInfo == null) {
                                var treeview = that.targetObj.find("#dataDictTreeView").data("kendoTreeView");
                                var nodes = treeview.dataSource.view();
                                var nodeElement = treeview.findByText(nodes[0].fullName);
                                treeview.select(nodeElement);
                                that.findGridData(null, nodes[0].dataCode);
                                that.nodeInfo = nodes[0];//保存选中树节点信息
                            }
                        }
                    });
                }
            }
        });
    },
    /*
     * 创建空列表
     */
    createGrid: function () {
        var columns = this.gridColumns();
        var that = this;
        this.sysUtils.createGird(this.targetObj.find("#dataDictList"), {
            dataSource: [],
            selectable: "single",
            reorderable: true,
            columnMenu: true,
            resizable: true,
            pageable: {
                input: true,
                numeric: false
            },
            columns: columns,
            dataBound: function () {
                that.targetObj.find("#dataDictList").find("tr:gt(0)").unbind("dblclick");
                that.targetObj.find("#dataDictList").find("tr:gt(0)").dblclick(function (e) {
                    that.openwindow(that.selectRow(), false);
                });
            }
        });
    },
    /**
     * 选中行
     */
    selectRow: function () {
        var grid = this.targetObj.find("#dataDictList").data("kendoGrid");
        var dataItem = grid.dataItem(grid.select());
        if (isEmpty(dataItem)) {
            return null;
        }
        var id = dataItem["id"];
        return id;
    },
    /**
     * 打开子系统信息窗口
     */
    openwindow: function (id, isEdit) {
        //打开查看窗口
        var title = "添加数据字典信息";
        this.editResult = null;
        var that = this;
        var opens = function () {
            that.isEdit = isEdit;
            that.openDivId = that.sysUtils.openWindow(that.openDivId, {
                title: title,
                height: "340px",
                width: "680px",
                resizable: false,
                content: "views/parkLotCenter/dataDict/dataDict_Edit.html"
            }, true);
        };
        var loadData = function () {
            JsonpAjax(baseApiPath + "basSystemDataDict/queryById/" + id, null, function (result) {
                if (0 === result.code) {
                    that.editResult = result.data;
                    opens();
                } else {
                    notification({title: "提示信息", message: result.message}, 'info');
                    return;
                }
            }, "GET");
        };
        if (isNotEmpt(id) && false == isEdit) {
            title = "查看数据字典信息";
            loadData();
        } else if (isEmpty(id) && true == isEdit) {
            title = "编辑数据字典信息";
            id = that.selectRow();
            if (null == id) {
                notification({title: "提示信息", message: "请选择需要编辑的数据字典信息!！"}, 'info');
                return;
            }
            loadData();
        } else {
            opens();
        }
    },
    /*
     * 重置按钮
     */
    resetInfo: function (e) {
        var that = $(e.target).data("that");
        that.sysUtils.setBindFieldNull(that.bindBaseModels.bindFieldArray);
    },
    findGridData: function (e, parentModelKey) {
        var that = this;
        if (isNotEmpt(e)) {
            that = $(e.target).data("that");
        }
        if (validityForm(that.targetObj)) {
            var jsonObj = that.sysUtils.getBindDocJson();
            if (isNotEmpt(parentModelKey)) {
                jsonObj["parentModelKey"] = parentModelKey;
            } else {
                //获取tree选中行
                var treeview = that.targetObj.find("#dataDictTreeView").data("kendoTreeView");
                var item = treeview.dataItem(treeview.select());
                jsonObj["parentModelKey"] = item["dataCode"];
            }
            var kendoGrid = that.targetObj.find("#dataDictList").data("kendoGrid");
            var urls = baseApiPath + "basSystemDataDict/queryWithPage";
            jsonObj["curdatetime"] = new Date().getTime();
            var dataSource = that.sysUtils.getDataSource({url: urls, data: jsonObj, dataType: "GET"});
            kendoGrid.setDataSource(dataSource);
            that.targetObj.find("input[gridid]")[0].checked = false;
        }
    },
    /*
     * 加载list 列表
     */
    gridColumns: function () {
        return [{
            width: 30,
            headerTemplate: '<input type="checkbox" gridId="dataDictList" onclick="gridCheckAll(this)" />',
            template: '<input name="childCheck" type="checkbox" value="${id}"/>'
        }, {
            title: "字典名称",
            field: "modelName"
        }, {
            title: "字典键",
            field: "modelKey"
        },
            {
                title: "字典值",
                field: "modelValue"
            },
            {
                title: "排序号",
                field: "sortNo"
            },
            {
                title: "创建时间",
                field: "createTime"
            },
            {
                title: "最后更新时间",
                field: "lastUpdateTime"
            }];
    },
    /**
     * 删除数据字典信息
     */
    delSystem: function () {
        //获取呗选中的选择框
        var that = this;
        var valStr = "";
        that.targetObj.find("input[name='childCheck']:checked").each(function () {
            valStr += "'" + $(this).val() + "',";
        });
        if ("" == valStr) {
            notification({title: "操作失败", message: "请勾选至少一条需要删除的记录!!"}, 'info');
            return;
        }
        notification({title: "确认信息", message: "确定需要删除选中的数据字典信息？"}, 'confirm', {
            callback: function () {
                let json = new Object();
                valStr = valStr.substring(0, valStr.length - 1);
                json["id"] = valStr;
                JsonpAjax(baseApiPath + "basSystemDataDict/delDataDictById", json, function (result) {
                    that.findGridData();
                    that.removeNode(valStr);
                });
            }
        });
    },
    /*
     * 增加节点
     */
    addNode: function (node) {
        var treeview = this.targetObj.find("#dataDictTreeView").data("kendoTreeView");
        treeview.append(node, treeview.select());
    },
    /**
     * 删除节点
     */
    removeNode: function (ids) {
        var idsArray = ids.replaceAll("'", "").split(",");
        var treeview = this.targetObj.find("#dataDictTreeView").data("kendoTreeView");
        var selectItems = treeview.dataItem(treeview.select()).items;
        for (var i = 0; i < selectItems.length; i++) {
            for (var j = 0; j < idsArray.length; j++) {
                if (selectItems[i]["id"] == idsArray[j]) {
                    var node = treeview.findByUid(selectItems[i]["uid"]);
                    treeview.remove(node);
                }
            }
        }
    },
    /**
     * 更新节点名称
     * @param nodeId
     * @param fullName
     */
    updateNode: function (nodeId, fullName) {
        var treeview = this.targetObj.find("#dataDictTreeView").data("kendoTreeView");
        var selectItems = treeview.dataItem(treeview.select()).items;
        for (var i = 0; i < selectItems.length; i++) {
            if (selectItems[i]["id"] == nodeId) {
                var li = this.targetObj.find("li[data-uid='" + selectItems[i]["uid"] + "']");
                li.find(".k-in:first").text(fullName);
            }
        }
    }
};


var parkDataDictEidt = function (targetObj) {
    this.sysUtils = new kendoUtils();
    this.targetObj = targetObj;
    this.init();
    return this;
};

parkDataDictEidt.prototype = {
    init: function () {
        var bindFieldArray = this.sysUtils.getBindFieldArray(this.targetObj);
        var bindFunctionArray = [{fName: "saveSystemInfo", fs: this.saveSystemInfo}, {
            fName: "closeWindow",
            fs: closeWindow
        }];
        this.bindBaseModels = new bindBaseModel(null, bindFieldArray, bindFunctionArray, null);
        this.sysUtils.bindDoucment(this.bindBaseModels, this.targetObj, this);
        this.sysUtils.setBindFieldValue({"parentModelKey": parkdictList.nodeInfo["dataCode"]});
        if (null != parkdictList.editResult) {
            this.sysUtils.setBindFieldValue(parkdictList.editResult);
            //键不允许更改
            this.targetObj.find("input[data-bind='value:modelKey']").attr("disabled", "disabled");
            if (false == parkdictList.isEdit) { //查看模式
                this.targetObj.find("input").attr("disabled", "disabled");
                this.targetObj.find("textarea").attr("disabled", "disabled");
                //this.targetObj.find(".save").remove();
                this.targetObj.find(".basicInfo-btn").remove();
            }
        }
    },
    //保存子系统信息
    saveSystemInfo: function (e) {
        var that = $(e.target).data("that");
        if (validityForm(that.targetObj)) {
            var dataDictInfo = that.sysUtils.getBindDocJson();
            var url = baseApiPath + "basSystemDataDict/save";
            if (true == parkdictList.isEdit) {
                url = baseApiPath + "basSystemDataDict/update";
                dataDictInfo["id"] = parkdictList.editResult["id"];
                dataDictInfo["modelKey"] = parkdictList.editResult["modelKey"];
                dataDictInfo["createBy"] = parkdictList.editResult["createBy"];
                dataDictInfo["createTime"] = parkdictList.editResult["createTime"];
                dataDictInfo["bottLevel"] = parkdictList.editResult["bottLevel"];
            }
            JsonpAjax(url, dataDictInfo, function (result) {
                closeWindow(); //关闭窗口
                parkdictList.findGridData();
                //动态在树形菜单上增加节点
                if (!parkdictList.isEdit) {
                    var nodeObj = {
                        hasChildren: false,
                        downChecked: true,
                        id: result.id,
                        fullName: result.modelName,
                        dataCode: result.modelKey,
                        dataType: ""
                    };
                    parkdictList.addNode(nodeObj);  //增加节点
                } else {   //编辑需要更新名称
                    parkdictList.updateNode(dataDictInfo["id"], dataDictInfo["modelName"]);
                }
            });
        }
    }
};